package com.uns1066.unsbar.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;

import org.springframework.util.Assert;

import com.uns1066.unsbar.common.CommonConstant;

/**
 * 文件上传帮助
 */
public class FileUtil {
	/**
	 * 将文本转换成字符串
	 * 
	 * @param srcFile
	 * @return
	 */
	public String toString(File srcFile) {
		StringBuffer content = new StringBuffer();
		try {
			FileReader fr = new FileReader(srcFile);
			BufferedReader br = new BufferedReader(fr);
			String line = br.readLine();
			while (line != null) {
				content.append(line);
				line = br.readLine();
			}
			br.close();
			fr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content.toString();
	}

	/**
	 * 将文件转换成字节数组
	 * 
	 * @param photo
	 * @return
	 */
	public byte[] toByteArray(File photo) {
		byte[] bytes = null;
		try {
			FileInputStream fis = new FileInputStream(photo);
			// 带缓存的读写
			BufferedInputStream bis = new BufferedInputStream(fis);
			// 转换写入的字节
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			// 读取一个字节
			int c = bis.read();
			// 判断是否为-1（读取到结尾）
			while (c != -1) {
				baos.write(c);// 写入到baos
				c = bis.read();
			}
			bis.close();
			fis.close();
			// 全部转换成字节数组
			bytes = baos.toByteArray();
			baos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 绘制指定大小的图片转换成字节数组
	 * 
	 * @param photo
	 * @param imageWidth
	 * @param imageHeight
	 * @return
	 */
	public byte[] bulidThumbnail(File photo, int imageWidth, int imageHeight) {
		byte[] bytes = null;
		// 得到元素图片对象
		try {
			Image src = ImageIO.read(photo);
			int oldWidth = src.getWidth(null);
			int oldHeight = src.getHeight(null);
			// 求比例
			float bili = (float) oldWidth / imageWidth;
			// 图片新的宽高
			int newWidth = imageWidth;
			if (oldWidth <= imageWidth) {
				newWidth = oldWidth;
			}
			int newHeight = (int) (oldHeight / bili);
			if (oldHeight <= newHeight) {
				newHeight = oldHeight;
			}
			// 画布
			BufferedImage bufferImage = new BufferedImage(imageWidth,
					imageHeight, BufferedImage.TYPE_INT_RGB);
			// 笔
			Graphics2D graphics = bufferImage.createGraphics();
			// 画布的背景为白色
			graphics.setBackground(Color.WHITE);
			// 划出一个矩形区域
			graphics.clearRect(0, 0, imageWidth, imageHeight);
			// 开始绘制新图片
			bufferImage.getGraphics().drawImage(src, 0, 0, newWidth, newHeight,null);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(baos);
			// 图片编码编码图片
			ImageIO.write(bufferImage, "jpg", bos);
			bytes = baos.toByteArray();
			bos.close();
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 保存上传图片到指定的路径
	 * 
	 * @param sourceFile
	 *            上传的图片
	 * @param outputDir
	 *            保存的路径
	 * @param outputFileName
	 *            保存的文件名
	 * @param outputWidth
	 *            保存的图片宽度
	 * @param outputHeight
	 *            保存图片的高度
	 * @param proportion
	 *            是否等比缩放
	 * @return 上传成功或失败
	 */
	public  static boolean  compressPic(File sourceFile, String newFilePath, int outputWidth, int outputHeight,boolean proportion) {
		try {
			Image img = ImageIO.read(sourceFile);
			// 判断图片格式是否正确
			if (img.getWidth(null) == -1) {
				Assert.isTrue(false, "不能读取，重试！");
				return false;
			} else {
				int newWidth = img.getWidth(null);
				int newHeight = img.getHeight(null);
				if (newWidth > outputWidth || newHeight > outputHeight) {
					// 判断是否是等比缩放
					if (proportion) {
						// 为等比缩放计算输出的图片宽度及高度
						double rate1 = ((double) img.getWidth(null))/ (double) outputWidth + 0.1;
						double rate2 = ((double) img.getHeight(null))/ (double) outputHeight + 0.1;
						// 根据缩放比率大的进行缩放控制
						double rate = rate1 > rate2 ? rate1 : rate2;
						newWidth = (int) (((double) img.getWidth(null)) / rate);
						newHeight = (int) (((double) img.getHeight(null)) / rate);
					} else {
						newWidth = outputWidth; // 输出的图片宽度
						newHeight = outputHeight; // 输出的图片高度
					}
				}
				BufferedImage tag = new BufferedImage((int) newWidth,(int) newHeight, BufferedImage.TYPE_INT_RGB);
				tag.getGraphics().drawImage(img, 0, 0, newWidth, newHeight,null);
				ImageIO.write(tag, "jpg", new File(newFilePath));
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 保存上传图片到指定的路径
	 * 
	 * @param InputStream
	 *            图片流
	 * @param outputDir
	 *            保存的路径
	 * @param outputFileName
	 *            保存的文件名
	 * @param outputWidth
	 *            保存的图片宽度
	 * @param outputHeight
	 *            保存图片的高度
	 * @param proportion
	 *            是否等比缩放
	 * @return 上传成功或失败
	 */
	public boolean compressPic(InputStream input, String outputDir, String outputFileName, int outputWidth, int outputHeight,boolean proportion) {
		try {
			createFolder(outputDir);
			Image img = ImageIO.read(input);
			// 判断图片格式是否正确
			if (img.getWidth(null) == -1) {
				Assert.isTrue(false, "不能读取，重试！");
				return false;
			} else {
				int newWidth = img.getWidth(null);
				int newHeight = img.getHeight(null);
				if (newWidth > outputWidth || newHeight > outputHeight) {
					// 判断是否是等比缩放
					if (proportion) {
						// 为等比缩放计算输出的图片宽度及高度
						double rate1 = ((double) img.getWidth(null))/ (double) outputWidth + 0.1;
						double rate2 = ((double) img.getHeight(null))/ (double) outputHeight + 0.1;
						// 根据缩放比率大的进行缩放控制
						double rate = rate1 > rate2 ? rate1 : rate2;
						newWidth = (int) (((double) img.getWidth(null)) / rate);
						newHeight = (int) (((double) img.getHeight(null)) / rate);
					} else {
						newWidth = outputWidth; // 输出的图片宽度
						newHeight = outputHeight; // 输出的图片高度
					}
				}
				BufferedImage tag = new BufferedImage((int) newWidth,(int) newHeight, BufferedImage.TYPE_INT_RGB);
				tag.getGraphics().drawImage(img, 0, 0, newWidth, newHeight,null);
				FileOutputStream out = new FileOutputStream(outputDir+ File.separator + outputFileName);
				ImageIO.write(tag, "jpg", out);
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 文件写入
	 * 
	 * @param file
	 * @param outputDir
	 * @param outputFileName
	 * @return
	 */
	public boolean fileWrite(File file, String outputDir, String outputFileName) {
		try {
			createFolder(outputDir);
			FileInputStream input = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(input);
			FileOutputStream out = new FileOutputStream(outputDir+ File.separator + outputFileName);
			byte[] byTmp = new byte[2048];
			int len = 0;
			while ((len = bis.read(byTmp)) != -1) {
				out.write(byTmp, 0, len);
			}
			input.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 文件写入
	 * 
	 * @param input
	 *            InputStream
	 * @param outputDir
	 *            保存的路径
	 * @param outputFileName
	 *            保存的文件名
	 * @return
	 */
	public boolean fileWrite(InputStream input, String outputDir,String outputFileName) {
		try {
			createFolder(outputDir);
			BufferedInputStream bis = new BufferedInputStream(input);
			FileOutputStream out = new FileOutputStream(outputDir+ File.separator + outputFileName);
			byte[] byTmp = new byte[2048];
			int len = 0;
			while ((len = bis.read(byTmp)) != -1) {
				out.write(byTmp, 0, len);
			}
			input.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 文件写入
	 * 
	 * @param byTmp
	 *            byte[]
	 * @param outputDir
	 *            保存的路径
	 * @param outputFileName
	 *            保存的文件名
	 * @return
	 */
	public boolean fileWrite(byte[] byTmp, String outputDir,
			String outputFileName) {
		try {
			createFolder(outputDir);
			FileOutputStream out = new FileOutputStream(outputDir+ File.separator + outputFileName);
			out.write(byTmp, 0, byTmp.length);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 生成唯一的文件名
	 * 
	 * @param suffix
	 * @return 0 原文件名 1 缩略图名
	 */
	public String[] getFileName(String suffix) {
		String[] str = new String[2];
		Date date = new Date();
		long time = date.getTime();
		Random rnd = new Random();
		int num = rnd.nextInt(10000);
		str[0] = time + "" + num + suffix;
		str[1] = time + "" + num + "_s" + suffix;
		return str;
	}

	/**
	 * 根据完整路径删除文件
	 * 
	 * @param dir
	 * @return
	 */
	public boolean deleteFile(String dir) {
		boolean bool = false;
		try {
			File file = new File(dir);
			if (file.exists()) {
				bool = file.delete();
			} else {
				bool = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return bool;
		}
		return bool;
	}

	/**
	 * 用户资源路径 不带文件名
	 * 
	 * @param request
	 * @return String [] 0 本地写入路径 1 网络路径
	 */
	public String[] getUserResourcesPath() {
		Calendar cal = Calendar.getInstance();// 使用日历类
		int year = cal.get(Calendar.YEAR);// 得到年
		int month = cal.get(Calendar.MONTH) + 1;// 得到月，因为从0开始的，所以要加1
		int day = cal.get(Calendar.DAY_OF_MONTH);// 得到天
		int hour = cal.get(Calendar.HOUR_OF_DAY);// 得到小时
		String[] path = new String[2];
		path[0] = CommonConstant.getLocalPath() + File.separator+ CommonConstant.getPrivateResources() + File.separator + year
				+ File.separator + month + File.separator + day
				+ File.separator + hour;
		path[1] = CommonConstant.getNetworkPath() + "/" + CommonConstant.getPrivateResources()+ "/" + year + "/" + month + "/" + day + "/" + hour;
		return path;
	}

	/**
	 * 用户公共资源路径
	 * 
	 * @param request
	 * @return String [] 0 本地写入路径 1 网络路径
	 */
	public String[] getPublicResourcesPath() {
		Calendar cal = Calendar.getInstance();// 使用日历类
		int year = cal.get(Calendar.YEAR);// 得到年
		int month = cal.get(Calendar.MONTH) + 1;// 得到月，因为从0开始的，所以要加1
		int day = cal.get(Calendar.DAY_OF_MONTH);// 得到天
		int hour = cal.get(Calendar.HOUR_OF_DAY);// 得到小时
		String[] path = new String[2];
		path[0] = CommonConstant.getLocalPath() + File.separator
				+ CommonConstant.getPrivateResources() + File.separator + year
				+ File.separator + month + File.separator + day
				+ File.separator + hour;
		path[1] = CommonConstant.getNetworkPath() + "/" + CommonConstant.getPublicResources()+ "/" + year + "/" + month + "/" + day + "/" + hour;
		return path;
	}

	/**
	 * 网络地址转换为本地地址
	 * 
	 * @param request
	 * @param str
	 * @param keyWord
	 * @return String [] 0 原图 1 缩略图
	 */
	public String[] netPathByLocalPath(String str, String keyWord) {
		String[] localPath = null;
		if (str != null) {
			String tmp = str.substring(str.lastIndexOf(keyWord), str.length()).replace("/", File.separator);
			localPath = new String[2];
			localPath[0] = CommonConstant.getLocalPath()+ File.separator + tmp;
			localPath[1] = CommonConstant.getLocalPath() + File.separator+ tmp.replace(".", "_s.");
		}
		return localPath;
	}

	/**
	 * 网络地址转换为本地地址
	 * 
	 * @param str
	 * @param root
	 * @param keyWord
	 * @return 0 原图 1 缩略图
	 */
	public String[] netPathByLocalPath(String str, String root, String keyWord) {
		String[] localPath = null;
		if (str != null) {
			String tmp = str.substring(str.lastIndexOf(keyWord), str.length()).replace("/", File.separator);
			localPath = new String[2];
			localPath[0] = root + File.separator + tmp;
			localPath[1] = root + File.separator + tmp.replace(".", "_s.");
		}
		return localPath;
	}

	/**
	 * 创建文件夹
	 * 
	 * @param outputDir
	 */
	private static void createFolder(String outputDir) {
		File file = new File(outputDir);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
}
